<?php
namespace app\controller;

use app\BaseController;
use app\model\Img;

/**
 * 文件操作
 * Class File
 * @package app\controller
 * @author 下雨吧จุ๊บ
 */
class File extends BaseController
{

    /**
     * @apiGroup 上传文件
     * @apiVersion 1.0.0
     * @api {POST} /file  上传文件
     * @apiDescription 上传文件
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '文件上传成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function save()
    {
        $data = input();
        $files = request()->file('image');
        $add = array();
        if (!empty($files)){
            foreach($files as $k=>$file){
                $add[$k]['url'] = '/uploads/'.\think\facade\Filesystem::putFile( '/'.date('Y/m/d'), $file);
                $add[$k]['table'] = $data['table'];
                $add[$k]['pid'] = $data['pid'];
                $add[$k]['name'] = $_FILES['image']['name'][$k];
            }
        }
        //添加数据库
        Img::insertAll($add);
        success($data,'上传完成');
    }

    public function index()
    {
        //引入类库
        include "PHPExcel/IOFactory.php";
        //elsx文件路径
        $inputFileName = "uploads/2021/06/02/20210602/1.xls";
        date_default_timezone_set('PRC');
        // 读取excel文件
        try {
            $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($inputFileName);
        } catch(Exception $e) {

        }
        // 确定要读取的sheet，什么是sheet，看excel的右下角，真的不懂去百度吧
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();

        // 获取excel文件的数据，$row=2代表从第二行开始获取数据
        for ($row = 2; $row <= $highestRow; $row++) {
            // Read a row of data into an array
            $rowData[] = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
            //这里得到的rowData都是一行的数据，得到数据后自行处理，我们这里只打出来看看效果
        }
        vard($rowData);
    }

    public function read()
    {
        $data = input();
        $data['list'] = Img::where('table',$data['table'])->where('pid',$data['id'])->select();
        success($data,'获取数据成功');
    }

    public function delete()
    {
        $data = input();
        //删除文件
        $filename = substr($data['url'],1);
        $result = unlink($filename);
        //删除数据
        Img::where('id',$data['fileid'])->delete();
        success(array(),'删除成功');
    }
}
